package com.itany.user.service.impl;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itany.constant.Constant;
import com.itany.dao.UserMapper;
import com.itany.exception.*;
import com.itany.pojo.User;
import com.itany.user.service.IUserService;
import com.itany.utils.MyHttpClientUtils;
import com.itany.vo.ActionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


@Service
@com.alibaba.dubbo.config.annotation.Service
public class UserService implements IUserService {

    @Autowired
    private UserMapper userMapper;



    //验证码生成
    private String mobileCode = "" + new Random().nextInt(100000);
    //TODO:验证码要放到redis并设置过期时间，防止一直发送短信

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public PageInfo<User> findUsers(Integer pageNo, Integer pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        List<User> list = userMapper.findUserAll();
        PageInfo<User> pageInfo = new PageInfo<User>(list);
        return pageInfo;
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public User login(User user) throws RequestParamsException,
            WrongUsernameOrPasswordException {
        if(StrUtil.isBlankIfStr(user.getPhone())||StrUtil.isBlankIfStr(user.getPassword())){
            throw new RequestParamsException("用户名、密码不能为空");
        }
        user.setPassword(SecureUtil.md5(user.getPassword()));
        User login = userMapper.login(user);
        if(login == null){
            throw new WrongUsernameOrPasswordException("用户名或密码错误");
        }
        return login;
    }


    /**
     * 获取手机验证码
     *
     * @param phone 手机号
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public ActionResult getphonecode(String phone) {
        Map<String, String> params = new HashMap<>();

        //短信发送内容
        String content = "您的验证码是：" + mobileCode + "。请不要把验证码泄露给其他人。";
        params.put("account", "C42022684");
        params.put("password", "87c95d006427d157debbea87efec597b");
        params.put("mobile", phone);
        params.put("content", content);
        params.put("format", "json");
        String jsonResult = MyHttpClientUtils.doPost("https://106.ihuyi.com/webservice/sms.php?method=Submit", params);
        JSONObject jsonObject = JSON.parseObject(jsonResult);
        ActionResult actionResult = new ActionResult();
        actionResult.setStatus(jsonObject.getInteger("code"));
        actionResult.setMsg(jsonObject.getString("msg"));
        return actionResult;
    }

    /**
     * 用户注册
     *
     * @param phone      电话
     * @param password   密码
     * @param repassword 确认密码
     * @param phonecode  手机验证码思
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void register(String phone, String password, String repassword, String phonecode) throws RequestParamsException, InconsistentPasswordsException, PhoneCodeErrorException, DuplicatePhoneException, MalformedPhoneException {
        if (StrUtil.isBlankIfStr(phone) || StrUtil.isBlankIfStr(password) || StrUtil.isBlankIfStr(repassword) || StrUtil.isBlankIfStr(phonecode)) {
            throw new RequestParamsException("请求参数缺失");
        }
        if (!password.equals(repassword)) {
            throw new InconsistentPasswordsException("两次输入密码不一致");
        }
        if (!mobileCode.equals(phonecode)) {
            throw new PhoneCodeErrorException("手机验证码输入错误");
        }
        if(!phone.matches(Constant.PHONE_REGEX)){
            throw new MalformedPhoneException("手机号格式错误");
        }
        User user = userMapper.selectByPhone(phone);
        if(user!=null){
            throw new DuplicatePhoneException("该手机号已经注册");
        }
         user = new User();
        user.setPhone(phone);
        System.out.println("手机验证码："+ mobileCode);
        user.setPassword(SecureUtil.md5(password));
        user.setFlag(Constant.ENABLE_STATUS);
        userMapper.insertUser(user);
    }



}
